"use strict";

const Controller = require("egg").Controller;

var cheerio = require("cheerio");

class HomeController extends Controller {
  // 添加博客 批量
  async index() {
    const { ctx } = this;
    let { ahref, state, url } = ctx.query;
    if (ahref == "" || ahref.search("http") == -1 || ahref.search("//") == -1)
      ctx.body = { code: 200, data: arr };

    let bufs = await this.ctx.curl(ahref);

    let bodys = String(bufs.data);

    // 处理成类jq
    const $ = cheerio.load(bodys, {
      decodeEntities: false,
    });

    let arr = [];

    $(".csdn-tracking-statistics").each((i, ite) => {
      $(ite).find("a").text().replace(/\s*/g, "").slice(2);
      arr.push({
        ahref: $(ite).find("a").prop("href"),
        title: $(ite).find("a").text().replace(/\s*/g, "").slice(2),
        state,
      });
    });

    arr.forEach(async (el) => {
      // 关闭
      await this.ctx.curl(url + "/csdnLook/add", {
        data: el,
      });
    });

    ctx.body = { code: 200, data: arr };
  }

  // csdn 刷访问
  async csdnLook() {
    const { ctx } = this;
    // 间隔时间    选择状态   轮询次数   访问类型
    let {
      timeout,
      StateArr,
      count,
      type,
      randomLv,
      twoUrl,
      title,
      tintroduce,
    } = ctx.query;

    // 查
    let ret = await this.app.mysql.query(
      `SELECT * FROM article WHERE state=${StateArr};`
    );
    let ind = ret.length;

    // 将任务独立出线程
    setTimeout(async () => {
      // 创建一个任务
      let data = await this.ctx.curl(twoUrl + "/task/add", {
        method: "POST",
        data: {
          tname: title,
          ttime_end: "",
          tstate: StateArr,
          ttotal: ind * count,
          tintroduce: tintroduce,
        },
      });
      let tid = JSON.parse(String(data.data)).data.insertId; // 插入的id

      // 添加轮询次数
      for (let index = 0; index < count; index++) {
        // 实现 访问
        for (let i = 0; i < ret.length; i++) {
          const element = ret[i];
          // 查看任务
          let taskOne = await this.ctx.curl(twoUrl + "/task/lsit/one", {
            method: "get",
            data: {
              tid,
            },
          });

          let taskOneObj = JSON.parse(String(taskOne.data)).data.results[0];

          // 终止任务
          if (taskOneObj.ttype == 1) break;

          // 实现随机
          if (type === "随机" && Math.random() < randomLv) continue;
          // 实现等待
          await setTimeGo(timeout);

          try {
            await this.ctx.curl(element.ahref);
            // console.log(element.ahref, "请求ok");

            // 改 博客表
            await this.app.mysql.query(
              `UPDATE article SET num=${++element.num} WHERE aid=${
                element.aid
              };`
            );
            // 跟新 任务表 完成数
            await this.app.mysql.query(
              `UPDATE task SET ttotal_end=${++taskOneObj.ttotal_end} WHERE tid=${tid};`
            );
          } catch (error) {
            // console.log(element.ahref, "访问失败", element.aid);
            // 跟新 任务表 异常数
            await this.app.mysql.query(
              `UPDATE task SET ttotal_unusual=${++taskOneObj.ttotal_unusual} WHERE tid=${tid};`
            );
          }
          // 访问结束
          if (index + 1 == count && ret.length - 1 === i) {
            // console.log("访问end");
            // 跟新 任务表 任务结束
            await this.app.mysql.query(
              `UPDATE task SET ttype=${1}, tintroduce='${
                taskOneObj.tintroduce
              }[正常结束]'  WHERE tid=${tid};`
            );
          }
        }
      }
    }, 1000);

    // 请求返回
    ctx.body = {
      code: 200,
      msg: "进行中",
      data: {
        timeEnd: timeout * ind * count,
        ind,
      },
    };

    // 延迟函数
    function setTimeGo(time) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve();
        }, time);
      });
    }
  }

  // 添加刷的博客
  async csdnLookAdd() {
    const { ctx } = this;

    // 避免重复插入
    let getData = await this.app.mysql.query(
      `SELECT * FROM article WHERE ahref='${ctx.query.ahref}';`
    );
    if (getData.length != 0)
      return (ctx.body = { code: 301, data: "链接已经存在" });

    // 添加数据
    let title = "DEFAULT";
    if (ctx.query.title != "") {
      title = `"${ctx.query.title}"`;
    }
    let state = "DEFAULT";
    if (ctx.query.state != "") {
      state = `"${ctx.query.state}"`;
    }
    let ret = await this.app.mysql.query(
      `INSERT INTO  article (ahref, title, state) VALUES ('${ctx.query.ahref}', ${title}, ${state});`
    );

    ctx.body = { code: 200, data: ret };
  }

  // 查询 博客 列表
  async csdnLookList() {
    const { ctx } = this;
    const { pageNum, pageSize, state } = ctx.query;
    // 条件查询
    let where = "";
    if (state != "" && Math.abs(Number(state)) >= 0) {
      where = `WHERE state=${Number(state)}`;
    }

    let results = await this.app.mysql
      .query(`SELECT * FROM article ${where} ORDER BY ahref
    LIMIT ${(pageNum - 1) * pageSize}, ${pageSize};`);
    let count = await this.app.mysql.query(
      `SELECT count(*) FROM article ${where};`
    );

    ctx.body = {
      code: 200,
      data: { results, pageNum, pageSize, count: count[0]["count(*)"] },
    };
  }

  // 删除文章
  async csdnLookDel() {
    const { ctx } = this;

    let ret = await this.app.mysql.query(
      `DELETE FROM article  WHERE aid=${ctx.query.aid};`
    );

    ctx.body = { code: 200, data: ret };
  }

  // 获取 分类列表
  async stateList() {
    const { ctx } = this;
    let results = await this.app.mysql.query(
      `SELECT DISTINCT state FROM article;`
    );

    ctx.body = {
      code: 200,
      data: { results },
    };
  }

  // 通过分类获取条数
  async stateNum() {
    const { ctx } = this;
    let results = await this.app.mysql.query(
      `SELECT COUNT(*) FROM article WHERE state=${ctx.query.state};`
    );
    ctx.body = {
      code: 200,
      data: { count: results[0]["COUNT(*)"] },
    };
  }

  // 测试接口
  async cs() {
    const { ctx } = this;
    let data = await this.ctx.curl("http://127.0.0.1:7002/task/add", {
      method: "POST",
      data: {
        tname: "测试项目",
        ttime_end: "",
        tstate: "1",
        ttotal: 1000,
        tintroduce: "测试一下下, 就是玩",
      },
    });
    ctx.body = {
      code: 200,
      data: { data: data.data },
    };
  }
}

module.exports = HomeController;
